package com.ling.service;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ElasticSearchService {
    private String esHost="http://localhost:9200/_search";

    private RestTemplate restTemplate=new RestTemplate();

    public ResponseEntity<String> getRecommendationByTitle(String key) {
        // ES 查询语句
        String requestStr = "{\"query\":{\"match_phrase\":{\"title\":{\"query\":\""+key+"\",\"slop\":10}}}}";
        // post方式请求数据
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(esHost, getRequestBody(requestStr), String.class);
        return stringResponseEntity;
    }

    public ResponseEntity<String> getRecommendationByContent(String key) {
        // ES 查询语句
        String requestStr = "{\"query\":{\"match_phrase\":{\"content\":{\"query\":\""+key+"\",\"slop\":10}}}}";
        // post方式请求数据
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(esHost, getRequestBody(requestStr), String.class);
        return stringResponseEntity;
    }

    private synchronized <T> HttpEntity<T> getRequestBody(T requestStr) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        return new HttpEntity<>(requestStr, headers);
    }
}
